package com.atguigu.flink.window;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * Created by Smexy on 2023/1/30
 *
 *      计算size = 5的基于元素个数的滚动窗口，统计每种传感器的vc最大的前3(top3)。
 *
 *
 *
 *
 */
public class Demo10_Process
{
    public static void main(String[] args) {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 3333);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .countWindow(5)
                   .process(new ProcessWindowFunction<WaterSensor, String, String, GlobalWindow>()
                   {
                       @Override
                       public void process(String key, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {

                           System.out.println("Demo10_Process.process");
                           //处理集合最方便的就是StreamAPI
                           List<WaterSensor> top3 = StreamSupport
                               .stream(elements.spliterator(), true)
                               .sorted((v1, v2) -> -v1.getVc().compareTo(v2.getVc()))
                               .limit(3)
                               .collect(Collectors.toList());

                           out.collect(key +"当前的vc前3是:"+top3);

                       }
                   })
                   .print();

        
                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
        
    }
}
